/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <div class="ai-flow__wrap">
        <div class="ai-flow__model">
            <div class="top-title">
                <lang>您可以选择AI Flow模板创建一个新的AI Flow</lang>
            </div>
            <div class="flow-model__total">
                <div v-for="(item,index) in flowModelList"
                     :key="index"
                     class="flow-model__item"
                     @click="_addFlow(index + 1)">
                    <i class="icon iconfont"
                       :class="item.iconCl"></i>
                    <div class="name text-center">
                        {{ item.name }}
                    </div>
                    <div class="content">
                        {{ item.content }}
                    </div>
                </div>
            </div>
        </div>
        <div class="add-null-flow">
            <sf-button-primary class="btn-blank creat-button white m-r15"
                               icon-cls="iconadd"
                               @click="_addFlow(0)">
                <lang>新增</lang>
            </sf-button-primary>
            <div class="content">
                <lang>您也可以选择创建一个空白AI Flow</lang>
            </div>
        </div>
        <div class="ai-flow__container">
            <sf-toolbar ref="toolbar">
                <div class="list-title">
                    <lang>AI Flow 列表</lang>
                </div>
                <sf-searchfield
                    v-model="searchParams.keyword"
                    class="pull-right"
                    placeholder="请输入关键字"
                    @clear="onEnterkey"
                    @trigger="onEnterkey" />
            </sf-toolbar>
            <div v-if="showEmptyAIFlow"
                 class="flow-total">
                <div
                    v-for="item in flowList"
                    :key="item.id"
                    class="flow-list__item">
                    <div class="flow-item__top">
                        <div class="left">
                            <div class="flow-title">
                                {{ item.flowName }}
                            </div>
                            <div class="flow-time">
                                <img src="../../../img/time_icon.png"
                                     alt="">
                                <div class="time">
                                    <lang>最近更新时间：</lang>
                                </div>
                                <div class="flow-time__text font-important">
                                    {{ encodeTime(item.updateTime) }}
                                </div>
                            </div>
                        </div>
                        <div class="right">
                            <sf-button
                                class="m-r15"
                                icon-cls="iconchakanxiangqing"
                                size="normalless"
                                @click="_enterAiFlowDetail(item)">
                                <lang>详情</lang>
                            </sf-button>
                            <sf-button
                                class="m-r15"
                                icon-cls="icon-comp-delete"
                                size="normalless"
                                @click="_deleteAiFlow(item)">
                                <lang>删除</lang>
                            </sf-button>
                        </div>
                    </div>
                    <div class="flow-item__center">
                        <div class="right  m-r30">
                            <lang>AI Flow模板：</lang>
                            <span class="font-important">{{
                                aiFlowTypeText(item.aiFlowType)
                            }}</span>
                        </div>
                        <div class="left m-r30">
                            <lang>数据源：</lang>
                            <span class="font-important">{{
                                item.dataSourceName || "-"
                            }}</span>
                        </div>
                        <div class="right  m-r30">
                            <lang>算法模板：</lang>
                            <span class="font-important">{{
                                item.algorithmName || "-"
                            }}</span>
                        </div>
                        <div class="right">
                            <lang>任务：</lang>
                            <span
                                class="font-important task-num"
                                @click="_enterTaskManager">{{ item.taskNum }}</span>
                        </div>
                    </div>
                </div>
            </div>
            <empty-panel v-else
                         :title="_('没有AI Flow')" />
            <sf-paging-bar
                v-if="flowList.length"
                :options="pageOptions"
                :layout="['pager']"
                @pagechange="_onPageChange" />
        </div>
    </div>
</template>
<script  lang="ts">
import { Vue, Component } from 'vue-property-decorator';
import EmptyPanel from 'src/components/empty_panel.vue';
import { encodeDate } from 'src/util/format';
const PAGE_COUNT = 5;

import addAiFlowForm from './label_form/add_aiflow_form.vue';
import store from 'src/vuex/store';
let userID = store.state.userId;

import trainingUrlAdapter from 'src/home/mod_common/training_url_adapter';
const FLOW_URLS = {
    get: trainingUrlAdapter('project'),
    delete: trainingUrlAdapter('flow'),
    post: trainingUrlAdapter(`user/${userID}/flow`)

};


interface FlowParams {
    flowName: string;
    updateTime: string;
    datasourceName: string;
    algorithmName: string;
    taskNum: number;
    projectId: number;
    aiFlowSnapshotId: number;
    aiFlowId: number;
    aiFlowType: number;
}

const AI_FLOW_TYPE_OBJ = {
    null:_('空白模板'),
    0:_('空白模板'),
    1:_('预测分析'),
    2:_('图像分类'),
    3:_('物体检测'),
    4:_('文本分类'),
    5:_('图计算')
};


@Component({
    components: {
        EmptyPanel
    }
})
export default class AIFlow extends Vue {
    flowList = [];
    searchParams = {
        keyword: '',
        pageNum: 0,
        pageSize: PAGE_COUNT,
        projectId: ''
    };
    pageOptions = {
        pageSize: PAGE_COUNT,
        activePage: 1,
        total: 0
    };
    aiFlowTotal = 0;
    showEmptyAIFlow = false;
    flowModelList = [{
        iconCl:'iconRectangleCopy',
        name:_('预测分析'),
        content:_('对结构化数据做出分类或数值预测')
    }, {
        iconCl:'icontuxiangimages19',
        name:_('图像分类'),
        content:_('识别一张图片中是否包含某种物体')
    }, {
        iconCl:'iconsaomiaojiancechazhao',
        name:_('物体检测'),
        content:_('识别图片中每个物体的位置和类别')
    }, {
        iconCl:'iconwenbenfenlei',
        name:_('文本分类'),
        content:_('识别一段文本的类别')
    }, {
        iconCl:'iconsaomiaojiancechazhao',
        name:_('图计算'),
        content:_('图计算')
    }];
    aiFlowType = 0;

    get projectId () {
        return this.$route.query.projectId || '';
    }
    mounted (): void {
        this.refreshGrid();
    }

    // 刷新grid
    async refreshGrid () {
        this.$mask();
        this.searchParams.projectId = this.projectId as string;
        let jsonData = await this.$ajax.get(`${FLOW_URLS.get}/${this.projectId}/flow`, this.searchParams);
        this.$unmask();
        let { success, msg, data } = jsonData;
        if (!success) {
            this.$showErr(msg || _('加载数据失败'));
            return;
        }
        this.flowList = data.list;
        this.showEmptyAIFlow = !!data.list.length;
        this.pageOptions.total = data.total;
        this.aiFlowTotal = data.total;
    }

     // 新增项目弹窗
    _createAiFlowFormWin () {
        if (!this.addAiFlowFormWin) {
                this.addAiFlowFormWin = this.$modal(addAiFlowForm, {
                autoDestory: true
            });
        }
        return this.addAiFlowFormWin;
    }

        //新增项目
    _addFlow (index: number) {
        if (index > 1) {
            return false;
        }

        this.aiFlowType = index;
        let formWin = this._createAiFlowFormWin();
        formWin.open({
            reset: true,
            title: _('新增AI Flow'),
            submit: () => {
                let ajaxParams = formWin.formRoot.getJsonValue();
                this.ajaxSubmitAiFlow(ajaxParams, formWin);
            }
        });
    }

    // 新增/编辑算法的卡片信息
    async ajaxSubmitAiFlow (params, formWin) {
        let aiFlowParams = {
            flowName: params.name,
            projectId: this.projectId,
            aiFlowType: this.aiFlowType
        };
        let jsonData = await this.$ajax.post(FLOW_URLS.post, aiFlowParams);
        let { success, msg, data } = jsonData;
        if (!success) {
            this.$showErr(msg || _('创建AI Flow失败'));
            return false;
        };

        this.$ok(msg || _('新增AI Flow成功'));
        formWin.hide();

        let flowQuery = {
            flow_name: params.name,
            aiFlowType: this.aiFlowType,
            aiFlowId: data.id
        };
        this.$router.push({
            path: `/project_manager/data_load`,
            query: Object.assign(this.$route.query, flowQuery)
        });
    }


    encodeTime (time: string) {
        return encodeDate(time);
    }
    _enterAiFlowDetail (item: FlowParams) {
        let flowQuery = {
            flow_name: item.flowName,
            aiFlowId: item.aiFlowId,
            aiFlowType:item.aiFlowType
        };
        this.$router.push({
            path: `/project_manager/data_load`,
            query: Object.assign(this.$route.query, flowQuery)
        });
    }
    _deleteAiFlow (params: FlowParams) {
        let title = params.flowName;
        // @ts-ignore
        this.$confirm({
            title: _('提示'),
            subTitle: _('确定要删除{0}吗？', title),
            msg: _('删除后，操作无法撤回，请谨慎操作!'),
            icon: 'warning',
            autoClose: true,
            callback: actionName => {
                if (actionName === 'submit') {
                    this.ajaxDeleteFlow(params);
                }
            }
        });
    }

    // 执行删除操作
    async ajaxDeleteFlow (params: FlowParams) {
        this.$mask();
        let jsonData = await this.$ajax.delete(
            `${FLOW_URLS.delete}/${params.aiFlowId}`
        );
        this.$unmask();
        let { success, msg } = jsonData;
        if (!success) {
            return this.$showErr(msg || _('删除失败'));
        }
        this.$ok(_('删除成功'));

        this.refreshGrid();
    }
    _onPageChange (pageNum: number) {
        Object.assign(this.searchParams, {
            pageNum: pageNum - 1
        });
        this.refreshGrid();
    }
    onEnterkey () {
        this.refreshGrid();
    }
    _enterTaskManager () {
        this.$router.push({
            path: `/project_manager/project_index/visual_task_manager`,
            query: Object.assign(this.$route.query)
        });
    }
    aiFlowTypeText (type: number) {
        return AI_FLOW_TYPE_OBJ[type];
    }
}
</script>
<style lang="less">
.ai-flow__wrap {
    width: 100%;
    height: calc(100% - 15px);
    .add-null-flow{
        display: flex;
        margin: 20px 0;
        align-items: center;
    }
    .ai-flow__model{
        .top-title{
            font-size: 14px;
            margin: 15px 0;
        }
        .flow-model__total{
            display: flex;
        }
        .flow-model__item{
            border:1px solid #dee3ed;
            margin-right: 15px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            width: 190px;
            height: 176px;
            background: #eee;
            &:first-of-type{
                background: #fff;
                cursor: pointer;
            }
            .iconfont{
                color: #1296db;
                font-size: 40px;
                margin-bottom: 10px;
                text-align: center;
            }
            .name{
                color: #14161A;
                font-size: 14px;
                font-weight: bold;
                margin-bottom: 10px;
            }
            .content{
                margin: 0 30px;
                line-height: 18px;
                text-align: center
            }
        }
    }
    .list-title{
        color: #14161A;
                font-weight: bold;
                    font-size: 16px;
    margin-left: 13px;
    line-height: 30px;
    }

    .flow-total {
        height: calc(100% - 88px);
        overflow: auto;
        .flow-list__item {
            border-bottom: 1px solid #dee3ed;
            height: 96px;
            color: #a3a3a3;
            display: flex;
            flex-direction: column;
            padding-left: 20px;
            overflow: auto;
            // &:last-child{
            //     border-bottom:none;
            // }
            .flow-item__top {
                display: flex;
                justify-content: space-between;
                margin-top: 18px;
                margin-bottom: 12px;
                .flow-title {
                    font-size: 16px;
                    color: #1f1f1f;
                    font-weight: 700;
                    margin-right: 20px;
                }
                .flow-time {
                    display: flex;
                    img {
                        width: 16px;
                        height: 16px;
                        margin-right: 4px;
                    }
                }
                .left {
                    display: flex;
                    align-items: center;
                }
            }
            .flow-item__center {
                display: flex;
                .task-num {
                    color: #204ed9;
                    cursor: pointer;
                }
            }
        }
    }
    .ai-flow__container {
        border: 1px solid #ddd;
        height: calc(100% - 282px);
        .cluster-empty-panel__container {
            height: calc(100% - 50px);
        }
    }
}
</style>
